<template>
  <div class="main">
    <div class="main_wrapper">
      <!-- 文章操作选项 -->
      <div class="option_wrapper" v-if="article">
        <ArticleOption
          :islike="this.article.islike"
          :likes="this.article.likes"
          :comments="this.commentCount"
          :isfavorite="this.article.isfavorite"
          :articleid="this.articleId"
          v-if="this.article"
        />
      </div>
      <div class="main-left" v-if="article">
        <div class="article_wrapper">
          <!-- 作者信息 -->
          <div class="head_box">
            <div class="author_logo">
              <router-link :to="{ path: '/user/'+this.userinfo.userid }" target="_blank">
                <img :src="this.userinfo.avatar" :alt="this.userinfo.username" />
              </router-link>
            </div>
            <div class="author_info">
              <ul>
                <li class="author_name">
                  <router-link
                    :to="{ path: '/user/'+this.userinfo.userid }"
                    target="_blank"
                  >{{this.userinfo.username}}</router-link>
                </li>
                <li class="post_date">{{this.article.posttime | dateFormat}}</li>
              </ul>
            </div>
            <div class="author_follow" v-if="changeBtn">
              <Button
                :type="!article.isfollow ? 'default':'primary'"
                long
                @click="changeFollow(article.isfollow,userinfo.userid)"
              >{{!this.article.isfollow ? '关注' :'已关注'}}</Button>
            </div>
          </div>
          <!-- 文章大图 -->
          <div
            class="screen_shot"
            v-lazy:background-image="this.article.screenshot"
            v-if="this.article.screenshot"
          ></div>
          <!-- 文章内容 -->
          <div class="content_box">
            <div class="article_title">{{this.article.title}}</div>
            <div
              class="article_content"
              v-html="this.article.content"
              v-lazy-container="{ selector: 'img' }"
            ></div>
          </div>
        </div>
        <!-- 评论 -->
        <div class="article_comments">
          <div class="title">评论</div>
          <div class="my_comment_box">
            <div class="avatar_box">
              <img :src="this.myavatar" alt class="my_avatar" />
            </div>
            <input
              class="my_comment"
              type="text"
              placeholder="输入评论"
              v-model="my_comment"
              @focus="write_comment"
            />

            <Button
              class="send_btn"
              type="primary"
              :disabled="!my_comment"
              @click="send_my_comment"
            >评论</Button>
          </div>
          <Comments :comments="commentData" v-if="commentData" @re_getcomments="getComments()" />
        </div>
      </div>
      <div class="main-right" v-if="article">
        <AboutAuthor :userinfo="userinfo" v-if="this.userinfo" />
      </div>
    </div>

    <NotFound v-if="iserror" />
  </div>
</template>

<script>
import Comments from "@/components/Comments.vue";
import NotFound from "@/views/NotFound.vue";
import AboutAuthor from "@/components/AboutAuthor.vue";
import ArticleOption from "@/components/ArticleOption.vue";
export default {
  components: {
    AboutAuthor,
    ArticleOption,
    Comments,
    NotFound
  },
  data() {
    return {
      myid: this.$store.state.user.uid,
      myavatar: this.$store.state.user.avatar,
      articleId: this.$route.params.aid,
      article: {},
      userinfo: {},
      iserror: false,
      loading: false, //防抖节流,
      commentData: [], //评论数据
      commentCount: "", //评论条数
      my_comment: "", //我的评论
      disabled: true //禁用发送按钮
    };
  },
  computed: {
    changeBtn() {
      if (this.myid != this.userinfo.userid) {
        return true;
      } else {
        return false;
      }
    }
  },
  methods: {
    // 过滤图片，添加懒加载标识
    replaceAllImg(content) {
      if (content !== null) {
        let newContent = content.replace(/<img[^>]*>/gi, function(
          str,
          capture
        ) {
          let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
          let url = str.match(srcReg);
          let mat = str.replace(/src=\"(.*)\"/gi, "data-src=" + url[1]);
          return mat;
        });
        return newContent;
      } else {
        return content;
      }
    },
    getArticleById(articleid) {
      let uid = this.$store.getters.user.uid;
      this.$axios
        .get("/getArticlesById", {
          params: {
            articleid: articleid,
            uid: uid
          }
        })
        .then(res => {
          if (res.data.code == 0 && res.data.data) {
            this.article = res.data.data;
            this.article.content = this.replaceAllImg(this.article.content);
            this.userinfo = res.data.data.userinfo;
          } else {
            // 出错了
            this.iserror = !this.iserror;
          }
        })
        .catch(e => {
          // 出错了
          this.iserror = !this.iserror;
          this.$Message.error({
            background: true,
            content: "获取失败",
            duration: 2.5
          });
          console.log(e.response);
        });
    },

    changeFollow(isfollow, followeeid) {
      // 先判断是否已登录
      let isLogin = this.$store.state.isAuthenticated;
      let uid = this.$store.state.user.uid;
      if (isLogin) {
        if (!this.loading) {
          let action;
          if (!isfollow) {
            // 关注
            action = "/follow";
          } else {
            // 取消关注
            action = "/unfollow";
          }
         this.$axios
            .get(action, {
              params: {
                followerid: uid,
                followeeid: followeeid
              }
            })
            .then(res => {
              if (res.data.code == 0) {
                this.article.isfollow = !this.article.isfollow;
              }
              this.loading = false;
            })
            .catch(err => {
              this.loading = false;
              console.log(err.response);
              this.$Message.error({
                background: true,
                content: "操作失败",
                duration: 2.5
              });
            });
        } else {
          return;
        }
      } else {
        // 弹出登录框
        this.$store.dispatch("setIsToLogin", true);
      }
    },

    //请求文章评论
    getComments() {
      this.$axios
        .get("/getAllComments", {
          params: {
            articleid: this.articleId
          }
        })
        .then(res => {
          this.$set(this, "commentData", res.data.data.comments);
          this.commentCount = res.data.data.count;
        })
        .catch(err => {
          console.log(err.response);
          this.$Message.error({
            background: true,
            content: "请求失败",
            duration: 2.5
          });
        });
    },

    // 点击评论框输入前判断是否登录
    write_comment() {
      let isLogin = this.$store.state.isAuthenticated;
      if (!isLogin)
        // 弹出登录框
        this.$store.dispatch("setIsToLogin", true);
    },
    // 发送评论
    send_my_comment() {
      let myid = this.$store.state.user.uid;
      if (!this.loading) {
        this.loading = true;
        this.$axios
          .post("/sendComment", {
            myid: myid,
            articleid: this.articleId,
            content: this.my_comment
          })
          .then(res => {
            // 清空评论框
            this.$set(this, "my_comment", "");
            this.loading = false;
            if (res.data.code == 0) {
              //重新请求评论信息
              this.getComments();
            } else {
              // 评论失败
              this.$Message.error({
                background: true,
                content: "评论失败",
                duration: 2.5
              });
            }
          })
          .catch(err => {
            this.loading = false;
            this.$set(this, "my_comment", "");
            // 评论失败
            this.$Message.error({
              background: true,
              content: "评论失败",
              duration: 2.5
            });
            console.log(err.response);
          });
      } else {
        return;
      }
    }
  },
  mounted() {
    this.getArticleById(this.articleId);
    this.getComments();
  }
};
</script>

<style lang='scss'>
.main {
  position: relative;
  max-width: 960px;
  margin: 0 auto;
  .main_wrapper {
    margin-top: 2rem;
    display: flex;
    flex-direction: row;
    width: inherit;

    .main-left {
      width: 700px;
      margin-right: 20px;
      background-color: #fff;
      margin-bottom: 4rem;

      .article_wrapper {
        padding: 18px;
        // 头部作者信息
        .head_box {
          display: flex;
          flex-direction: row;
          align-items: center;
          height: 3rem;
          margin-bottom: 2rem;
          .author_logo {
            a > img {
              display: block;
              width: 50px;
              height: 50px;
              border-radius: 4px;
            }
          }
          .author_info {
            margin-left: 15px;
            flex: 1;
            ul {
              height: 100%;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              .author_name {
                flex: 1;
                a {
                  color: #333;
                  font-size: 16px;
                  font-weight: 700;
                }
              }
              .post_date {
                font-size: 12px;
                // 字体间距
                letter-spacing: 1px;
                color: #909090;
              }
            }
          }
          .author_follow {
            display: flex;
            align-items: flex-end;
            width: 4.5rem;
          }
        }
        // 封面大图展示
        .screen_shot {
          margin-bottom: 2rem;
          width: 100%;
          padding-top: 55%;
          background-repeat: no-repeat;
          background-position: 50%;
          background-size: cover;
        }
        // 文章内容样式
        .content_box {
          padding: 1.5rem 0 2rem 0;
          border-bottom: 1px solid #b6b6b6;

          .article_title {
            color: #333;
            font-size: 1.8rem;
            font-weight: 700;
            line-height: 1.5;
            padding-bottom: 1rem;
          }
          .article_content {
            img {
              width: 100%;
            }
          }
        }
      }
      .article_comments {
        padding: 1.5rem 0;
        .title {
          padding: 0 18px;
          text-align: center;
          font-size: 1.1rem;
          // font-weight: 600;
          height: 3rem;
          line-height: 3rem;
        }
        .my_comment_box {
          margin: 0 1rem 2rem;
          padding: 1.5rem 1rem;
          display: flex;
          flex-direction: row;
          align-items: center;
          background-color: #fafbfc;
          // border-radius: 4px;
          .avatar_box {
            height: 2.8rem;
            width: 2.8rem;
            border-radius: 4px;
            background-color: #fff;
            .my_avatar {
              width: inherit;
              height: inherit;
            }
          }

          .my_comment {
            height: 2.5rem;
            margin: 0.5rem;
            padding: 0 0.5rem;
            flex: 1;
            border: 1px solid #eee;
            border-radius: 4px;
            outline: none;
          }
          .my_comment:focus {
            border: 1px solid #007fff;
          }
        }
      }
    }
    .main-right {
      flex: 1;
    }
  }
}

@media screen and (max-width: 960px) {
  .main .main_wrapper .main-left {
    width: 100%;
    margin: 0;
  }
  .main .main_wrapper .main-right {
    display: none;
  }
}
</style>